package net.googlecode.demenkov.utils;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

/**
 * Class that manages sending emails
 *
 * @author Demenkov Yura
 */
public class MailManager {
    /**
     * email to send from
     */
    private String voteUpEmail;
    /**
     * password for email to send from
     */
    private String voteUpPassword;

    /**
     * Sends registration confirm letter to person to confirm registration.
     * Uses voteUpEmail and voteUpPassword for authorization.
     *
     * @param mailTo email of person to send
     * @param url    link to confirm registration that will be sent to person's email
     * @throws AddressException
     * @throws MessagingException
     */
    public void sendEmailMessage(String mailTo, String url) throws AddressException, MessagingException {
        try {
            Email email = new SimpleEmail();
            email.setHostName("smtp.gmail.com");
            email.setSmtpPort(587);
            email.setAuthenticator(new DefaultAuthenticator(getVoteUpEmail(), getVoteUpPassword()));
            email.setTLS(true);
            email.setFrom("VoteUpNow@gmail.com");
            email.setSubject("Confirm registration");
            email.setMsg("Thank you for registration in VoteUp. Please, confirm your registration by clicking the fillowing link: " + url);
            email.addTo(mailTo);
            email.send();
        } catch (EmailException e) {
            throw new MessagingException();
        }
    }

    /**
     * Sets voteUpEmail
     *
     * @param voteUpEmail
     */
    public void setVoteUpEmail(String voteUpEmail) {
        this.voteUpEmail = voteUpEmail;
    }

    /**
     * Gets voteUpEmail
     *
     * @return voteUpEmail
     */
    public String getVoteUpEmail() {
        return voteUpEmail;
    }

    /**
     * Sets voteUpPassword
     *
     * @param voteUpPassword
     */
    public void setVoteUpPassword(String voteUpPassword) {
        this.voteUpPassword = voteUpPassword;
    }

    /**
     * Gets voteUpPassword
     *
     * @return voteUpPassword
     */
    public String getVoteUpPassword() {
        return voteUpPassword;
    }
}
